import numpy as np
from keras import models, layers
from keras.datasets import reuters
from keras.utils import to_categorical
from matplotlib import pyplot as plt

(train_data, train_labels), (test_data, test_labels) = reuters.load_data(num_words=10000)

print(test_data)
# 将数据转为0，1数据向量
def vectorize_sequences(sequences, dimension=10000):
    results = np.zeros((len(sequences), dimension))


    for i, sequence in enumerate(sequences):
        results[i, sequence] = 1.

    return results

x_train = vectorize_sequences(train_data)
x_test = vectorize_sequences(test_data)

# 独热编码处理
one_hot_train_labels = to_categorical(train_labels)
one_hot_test_labels = to_categorical(test_labels)

# 网络层构建
model = models.Sequential()
model.add(layers.Dense(64, activation='relu', input_shape=(10000,)))
model.add(layers.Dense(64, activation='relu'))
model.add(layers.Dense(46, activation='softmax'))
print(len(one_hot_test_labels[0]))
# 编译模型
model.compile(optimizer='rmsprop',
              loss = 'categorical_crossentropy',
              metrics=['accuracy'])

# 留出验证集
x_val = x_train[:1000]
partial_x_train = x_train[1000:]

y_val = one_hot_train_labels[:1000]
partial_y_train = one_hot_train_labels[1000:]

# 训练模型
history = model.fit(partial_x_train, partial_y_train, epochs=20, batch_size=512, validation_data=(x_val, y_val))

# 绘图
loss = history.history['loss']
val_loss = history.history['val_loss']
epochs = range(1, len(loss) + 1)

plt.plot(epochs, loss,'bo', label = 'Training loss')
plt.plot(epochs, val_loss,'b', label='Validation loss')
plt.title('Traing and valitdation loss')
plt.xlabel('Epochs')
plt.legend()
plt.show()



